const Koa=require("koa");
const Router=require("koa-router");//路由
const cors = require('koa2-cors');//跨域
const bodyParser = require('koa-bodyparser');//获取body请求参数
const MysqlPool = require('./mysqlPool');//数据库连接池
const fs = require('fs');
let jsonFile = './log.json';
let jsonObj = require(jsonFile);
//实例化
const app=new Koa();
const router=new Router();
const mysqlPool = new MysqlPool();
const poolQuery = mysqlPool.getPool();
let apiRouters=[];//路由list
let projectList=[];//项目list
let projectObj={};//项目标识
//注册所有mockApi
poolQuery('SELECT * FROM project',(err,projectItem)=>{
  if(err){
    console.log(err);
    return;
  }
  projectList=projectItem;
  for (let i = 0; i < projectList.length; i++) {
    projectObj[projectList[i].id]=projectList[i].value
  }
  poolQuery('SELECT * FROM api',(err,result)=>{
    if(err){
      console.log(err);
      return
    }
    let _apiList=result;
    apiRouters=_apiList.map(item=>{
      router[item.method](`/${projectObj[item.projectId]}${item.path}`,async ctx=>{//注册路由
        ctx.status=200;
        ctx.body=JSON.parse(item.successMessage);
      })
      return `/${projectObj[item.projectId]}${item.path}/${item.method}`//标识路由
    })
    console.log("mock路由注册成功")
  });
})
//记录最近一次操作并重启服务
let handLog=(e)=>{
  jsonObj.message={
    method:e,
    date:new Date()
  };
  fs.writeFile(jsonFile, JSON.stringify(jsonObj, null, 2), (err) => {
    if (err) {
      console.log(err);
    }
  });
}

router.get("/", async ctx=>{
  ctx.body="ok"
})
//项目
// 查询项目list
router.get("/project/mock/query",async ctx=>{
  ctx.status=200;
  try{
    let _getSql="SELECT * FROM project";
    const result = await poolQuery(_getSql);
    ctx.body={
      errorCode: "",
      errorMessage: "",
      result: true,
      data: result
    }
  } catch(e) {
    ctx.body={
      errorCode: "",
      errorMessage: "请求失败",
      result: false,
      data: null
    }
  }
})
//添加项目
router.post("/project/mock/add",async ctx=>{
  ctx.status=200;
  let _data=ctx.request.body;
  if(!_data.name||!_data.value){
    ctx.body={
      errorCode: "",
      errorMessage: "请求参数错误",
      result: false,
      data: null
    }
    return
  }else if(projectList.filter(item=>item.name==_data.name||item.value==_data.value).length){
    ctx.body={
      errorCode: "",
      errorMessage: "项目名或项目类型重复",
      result: false,
      data: null
    }
    return
  }
  try {
    let _addSql="INSERT INTO project(name,value) VALUES(?,?)";
    let _addSqlParams = [_data.name, _data.value];
    await poolQuery(_addSql,_addSqlParams);
    ctx.body={
      errorCode: "",
      errorMessage: "",
      result: true,
      data: null
    }
  } catch (error) {
    ctx.body={
      errorCode: "",
      errorMessage: "请求失败",
      result: false,
      data: null
    }
  }

})
//删除项目
router.delete("/project/mock/delete/:id",async ctx=>{
  ctx.status=200;
  let _data=ctx.params;
  try {
    let _apiListSpl="SELECT * FROM api WHERE projectId = ?";
    let _projectId=[_data.id];
    let _delSql = 'DELETE FROM project where id = ?';
    let _delSqlParams=[_data.id];
    let _apiList=await poolQuery(_apiListSpl,_projectId);
    if(_apiList.length){
      ctx.body={
        errorCode: "",
        errorMessage: "使用中的项目无法删除！",
        result: false,
        data: null
      }
      return;
    }
    await poolQuery(_delSql,_delSqlParams);
    ctx.body={
      errorCode: "",
      errorMessage: "",
      result: true,
      data: null
    }
  } catch (error) {
    ctx.body={
      errorCode: "",
      errorMessage: "请求失败",
      result: false,
      data: null
    }
  }

})
//接口
router.get("/api/mock/query",async ctx=>{
  ctx.status=200;
  try{
    let _data=ctx.query;
    var _dataKey=Object.keys(_data);
    var _apiKey=["projectId"];
    let _getSql="SELECT * FROM api";
    if(_dataKey&&_dataKey.length){
      for (let i = 0; i < _dataKey.length; i++) {
        if(_apiKey.indexOf(_dataKey[i])==-1){
          ctx.body={
            errorCode: "",
            errorMessage: "参数错误",
            result: false,
            data: null
          }
          return;
        }
      }
      _getSql+=` WHERE projectId=${_data["projectId"]}`
    }
    const result = await poolQuery(_getSql);
    ctx.body={
      errorCode: "",
      errorMessage: "",
      result: true,
      data: result
    }
  } catch(e) {
    console.log(e);
    ctx.body={
      errorCode: "",
      errorMessage: "请求失败",
      result: false,
      data: null
    }
  }
})
//添加api接口
router.post("/api/mock/add",async ctx=>{
  ctx.status=200;
  let _data=ctx.request.body;
  if(!_data.path||!_data.method||!_data.successMessage||!_data.errorMessage||!_data.projectId){
    ctx.body={
      errorCode: "",
      errorMessage: "请求参数错误",
      result: false,
      data: null
    }
    return
  }else if(apiRouters.indexOf(`/${projectObj[_data.projectId]}${_data.path}/${_data.method}`)!==-1){
  //   apiRouters.push(`${_data.path}/${_data.method}`)
  // }else{
    ctx.body={
      errorCode: "",
      errorMessage: "请求路径或请求方式重复",
      result: false,
      data: null
    }
    return
  }
  try{
    let _addSql="INSERT INTO api(path,method,successMessage,errorMessage,projectId) VALUES(?,?,?,?,?)";
    let _addSqlParams = [_data.path, _data.method,JSON.stringify(_data.successMessage),JSON.stringify( _data.errorMessage),_data.projectId];
    await poolQuery(_addSql,_addSqlParams);
    router[_data.method](`/${projectObj[item.projectId]}${item.path}`,async ctx=>{
      ctx.status=200;
      ctx.body=JSON.parse(_data.successMessage);
    })
    apiRouters.push(`/${projectObj[_data.projectId]}${_data.path}/${_data.method}`)
    ctx.body={
      errorCode: "",
      errorMessage: "",
      result: true,
      data: null
    }
  }catch(e){
    ctx.body={
      errorCode: "",
      errorMessage: "请求失败",
      result: false,
      data: null
    }
  }
  
})
//修改api接口
router.put("/api/mock/put",async ctx=>{
  console.log(ctx.request.body);
  ctx.status=200;
  let _data=ctx.request.body;
  if(!_data.id||!_data.path||!_data.method||!_data.successMessage||!_data.errorMessage||!_data.projectId){
    ctx.body={
      errorCode: "",
      errorMessage: "请求参数错误",
      result: false,
      data: null
    }
    return
  }
  try{
    let _putSql="UPDATE api SET path = ?,method = ?,successMessage = ?,errorMessage = ?,projectId = ? WHERE id = ?";
    let _putSqlParams = [_data.path, _data.method,JSON.stringify(_data.successMessage),JSON.stringify(_data.errorMessage),_data.projectId,_data.id];
    await poolQuery(_putSql,_putSqlParams);
    handLog("put")
    ctx.body={
      errorCode: "",
      errorMessage: "",
      result: true,
      data: null
    }
  }catch(e){
    console.log(e)
    ctx.body={
      errorCode: "",
      errorMessage: "请求失败",
      result: false,
      data: null
    }
  }
})

//删除api接口
router.delete("/api/mock/delete/:id",async ctx=>{
  ctx.status=200;
  let _data=ctx.params;
  try {
    let _delSql = 'DELETE FROM api where id = ?';
    let _delSqlParams=[_data.id];
    await poolQuery(_delSql,_delSqlParams);
    handLog("delete")
    ctx.body={
      errorCode: "",
      errorMessage: "",
      result: true,
      data: null
    }
  } catch (error) {
    ctx.body={
      errorCode: "",
      errorMessage: "请求失败",
      result: false,
      data: null
    }
  }

})
//配置路由
app.use(cors()).use(bodyParser()).use(router.routes()).use(router.allowedMethods());
const port =process.env.PORT||5000;
app.listen(port,()=>{
  console.log(`Server runing on port ${port}`);
}) 